package info.cs52.fes.dao;

import info.cs52.fes.Application;
import info.cs52.fes.data.User;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

public class UserDAO {

	public static User findByName(String name) {
		EntityManager em = Application.getEntityManager();
		Query query = em.createQuery("select d from User d where name=:name");
		query.setParameter("name", name);
		List users = query.getResultList();
		if (users.size() == 1) {
			return (User) users.get(0);
		}
		return null;
	}
	
	public static User findByServiceUserId(String id) {
		EntityManager em = Application.getEntityManager();
		Query query = em.createQuery("select d from User d where serviceUserId=:id");
		query.setParameter("id", id);
		List users = query.getResultList();
		if (users.size() == 1) {
			return (User) users.get(0);
		}
		return null;
	}

	public static User find(Long id) {
		EntityManager em = Application.getEntityManager();
		return em.find(User.class, id);
	}

	public static void persist(User user) {
		EntityManager em = Application.getEntityManager();
		EntityTransaction tr = em.getTransaction();
		tr.begin();
		em.persist(user);
		tr.commit();
	}

	public static void delete(String id) {
		EntityManager em = Application.getEntityManager();
		EntityTransaction tr = em.getTransaction();
		tr.begin();
		em.remove(em.getReference(User.class, id)); 
		tr.commit();
	}

}
